package cn.gson.oasys.controller.daymanage;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;

import com.alibaba.fastjson.JSONObject;

import cn.gson.oasys.model.dao.daymanagedao.DaymanageDao;
import cn.gson.oasys.model.dao.system.StatusDao;
import cn.gson.oasys.model.dao.system.TypeDao;
import cn.gson.oasys.model.dao.user.UserDao;
import cn.gson.oasys.model.entity.schedule.ScheduleList;
import cn.gson.oasys.model.entity.system.SystemStatusList;
import cn.gson.oasys.model.entity.system.SystemTypeList;
import cn.gson.oasys.model.entity.user.User;
import cn.gson.oasys.services.daymanage.DaymanageServices;
import cn.gson.oasys.services.process.ProcessService;

@Controller
@RequestMapping("/")
public class DaymanageController {
	@Autowired
	DaymanageDao daydao;
	@Autowired
	UserDao udao;
	@Autowired
	DaymanageServices dayser;
	@Autowired
	StatusDao statusdao;
	@Autowired
	TypeDao typedao;
	@Autowired
	ProcessService ps;
	
	@RequestMapping("daymanage")
	private String daymanage(@SessionAttribute("userId") Long userid,
			Model model,@RequestParam(value="page",defaultValue="0") int page,
			@RequestParam(value="size",defaultValue="10") int size
			) {
		List<SystemTypeList> types = typedao.findByTypeModel("aoa_schedule_list");
		List<SystemStatusList> statuses = statusdao.findByStatusModel("aoa_schedule_list");
		List<Order> orders=new ArrayList<>();
		orders.add(new Order(Direction.DESC, "statusId"));
		orders.add(new Order(Direction.DESC, "createTime"));
		Sort sort=new Sort(orders);
		Pageable pa=new PageRequest(page, size,sort);
		User user = udao.findOne(userid);
		Page<ScheduleList> myday = daydao.findByUser(user, pa);
		
		List<ScheduleList> scheduleLists = myday.getContent();
		
		model.addAttribute("schedules",scheduleLists);
		model.addAttribute("types",types);
		model.addAttribute("statuses",statuses);
		model.addAttribute("page", myday);
		model.addAttribute("url", "daymanagepaging");
		model.addAttribute("ismyday", 1);
		return "daymanage/daymanage";
	}
	
	@RequestMapping("daymanagepaging")
	private String daymanagepaging(@SessionAttribute("userId") Long userid,
			Model model,@RequestParam(value="page",defaultValue="0") int page,
			@RequestParam(value="size",defaultValue="10") int size
			){
		
		List<SystemTypeList> types = typedao.findByTypeModel("aoa_schedule_list");
		List<SystemStatusList> statuses = statusdao.findByStatusModel("aoa_schedule_list");
		
		Sort sort=new Sort(new Order(Direction.ASC,"user"));
		Pageable pa=new PageRequest(page, size,sort);
		User user = udao.findOne(userid);
		Page<ScheduleList> myday = daydao.findByUser(user, pa);
		
		List<ScheduleList> scheduleLists = myday.getContent();
		model.addAttribute("types",types);
		model.addAttribute("statuses",statuses);
		model.addAttribute("schedules",scheduleLists);
		model.addAttribute("page", myday);
		model.addAttribute("url", "daymanagepaging");
		model.addAttribute("ismyday", 1);
		return "daymanage/daymanagepaging";
	}
	@RequestMapping("aboutmeday")
	private String aboutmeday(@SessionAttribute("userId") Long userid,
			Model model,@RequestParam(value="page",defaultValue="0") int page,
			@RequestParam(value="size",defaultValue="10") int size
			){
		
		List<SystemTypeList> types = typedao.findByTypeModel("aoa_schedule_list");
		List<SystemStatusList> statuses = statusdao.findByStatusModel("aoa_schedule_list");
		
		Sort sort=new Sort(new Order(Direction.ASC,"user"));
		Pageable pa=new PageRequest(page, size,sort);
		User user = udao.findOne(userid);
		List<User> users = new ArrayList<>();
		users.add(user);
		Page<ScheduleList> aboutmeday = daydao.findByUsers(users, pa);
		
		List<ScheduleList> scheduleLists = aboutmeday.getContent();
		
		model.addAttribute("schedules",scheduleLists);
		model.addAttribute("types",types);
		model.addAttribute("statuses",statuses);
		model.addAttribute("page", aboutmeday);
		model.addAttribute("url", "aboutmedaypaging");
		
		return "daymanage/daymanage";
	}
	
	@RequestMapping("aboutmedaypaging")
	public String aboutmedaypaging(@SessionAttribute("userId") Long userid,
			Model model,@RequestParam(value="page",defaultValue="0") int page,
			@RequestParam(value="size",defaultValue="10") int size
			){
		
		List<SystemTypeList> types = typedao.findByTypeModel("aoa_schedule_list");
		List<SystemStatusList> statuses = statusdao.findByStatusModel("aoa_schedule_list");
		
		Sort sort=new Sort(new Order(Direction.ASC,"user"));
		Pageable pa=new PageRequest(page, size,sort);
		User user = udao.findOne(userid);
		List<User> users = new ArrayList<>();
		users.add(user);
		Page<ScheduleList> aboutmeday = daydao.findByUsers(users, pa);
		
		List<ScheduleList> scheduleLists = aboutmeday.getContent();
		
		model.addAttribute("schedules",scheduleLists);
		model.addAttribute("types",types);
		model.addAttribute("statuses",statuses);
		model.addAttribute("page", aboutmeday);
		
		model.addAttribute("url", "aboutmedaypaging");
		
		return "daymanage/daymanagepaging";
	}
	
	@RequestMapping("dayedit")
	private String dayedit(@RequestParam(value="rcid",required=false) Long rcid,
			@RequestParam(value="page",defaultValue="0") int page,
			@RequestParam(value="size",defaultValue="10") int size,
			Model model
			){
		ps.user(page, size, model);
		List<SystemTypeList> types = typedao.findByTypeModel("aoa_schedule_list");
		List<SystemStatusList> statuses = statusdao.findByStatusModel("aoa_schedule_list");
		ScheduleList rc = null;
		if(rcid!=null){
			rc = daydao.findOne(rcid);
			System.out.println(rc);
		}
		
		model.addAttribute("types",types);
		model.addAttribute("statuses",statuses);
		model.addAttribute("rc",rc);
		return "daymanage/editday";
	}
	
	@RequestMapping("addandchangeday")
	public String addandchangeday(ScheduleList scheduleList,@RequestParam("shareuser") String shareuser,BindingResult br,
			@SessionAttribute("userId") Long userid){
		User user = udao.findOne(userid);
		System.out.println(shareuser);
		List<User> users = new ArrayList<>();
		
		System.out.println(users.size());
		StringTokenizer st = new StringTokenizer(shareuser, ";");
		
		while (st.hasMoreElements()) {
			users.add(udao.findByUserName(st.nextToken()));
		}
	
		scheduleList.setUser(user);
		if(users.size()>0){
			scheduleList.setUsers(users);
		}
		System.out.println(scheduleList);
		
		daydao.save(scheduleList);
		this.pushMessage(users);
		return "/daymanage";
	}

	public static String accessToken = "";
	/**
	 * 日程消息提醒推送
	 * @param users
	 */
	private void pushMessage(List<User> users) {
		// 获取accesstoken
		accessToken = this.getAccessToken();

		// 遍历user，获取手机号
		if (users != null && users.size() > 0) {
			StringBuffer userIds = new StringBuffer();
			for (User user : users) {
				// 将手机号转为userId
				String userId = this.tel2userId(user.getUserTel());
				if (userId != null) {
					userIds.append(userId).append("|");
				}
			}
			if (userIds.length() > 0) {
				// 去除最后一个 “|”
				userIds.deleteCharAt(userIds.length() - 1);
				// 发送消息
				this.sendMessage(userIds.toString());
			}
		}
	}

	private void sendMessage(String userIds) {
		// 创建客户端
		CloseableHttpClient httpClient = HttpClients.createDefault();
		String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accessToken;
		CloseableHttpResponse response = null;
		HttpEntity httpEntity = null;
		// body的String格式
		String result = null;

		// 使用的打卡这个应用
		try {
			HttpPost request = new HttpPost(url);
			// 添加参数
			String json = "{\n" +
					"  \"touser\":\"" + userIds + "\",\n" +
					" \"msgtype\" : \"text\", \n" +
			        " \"agentid\" :3010011,\n" +
					"\"text\" : { \n" +
					" \"content\" :\"日程提醒，微信消息推送接口的测试!\"\n" +
					" },\n" +
					" \"safe\":0,\n" +
					" \"enable_id_trans\": 0,\n" +
					" \"enable_duplicate_check\": 0,\n" +
					" \"duplicate_check_interval\":1800\n" +
					"}";

			StringEntity stringEntity = new StringEntity(json, "UTF-8");
			stringEntity.setContentType("application/json");
			request.setEntity(stringEntity);
			// 发送请求并返回结果
			response = httpClient.execute(request);
			// 获取返回body
			httpEntity = response.getEntity();
			result = EntityUtils.toString(httpEntity,"UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if (httpClient != null) {
					httpClient.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (httpEntity != null) {
			JSONObject jsonObject = JSON.parseObject(result);
			String errcode = jsonObject.getString("errcode");
			if ("0".equals(errcode)) {
				// 发送成功
				System.out.println("发送成功");
			} else {
				// 发送失败
				System.out.println("发送失败");
			}
		}
	}

	private String tel2userId(String userTel) {
		String userId = null;
		// 创建客户端
		CloseableHttpClient httpClient = HttpClients.createDefault();
		// 存放url
		String url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserid?access_token=" + accessToken;
		// 存放返回结果
		CloseableHttpResponse response = null;
		// 存放返回结果的body
		HttpEntity httpEntity = null;
		// body的String格式
		String result = null;
		try {
			HttpPost request = new HttpPost(url);
			// 添加参数
			String json = "{\n" +
					" \"mobile\":\"" + userTel + "\"\n" +
					"}";
			StringEntity stringEntity = new StringEntity(json, "UTF-8");
			stringEntity.setContentType("application/json");
			request.setEntity(stringEntity);
			// 发送请求并获取返回结果
			response = httpClient.execute(request);
			httpEntity = response.getEntity();
			result = EntityUtils.toString(httpEntity,"UTF-8");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if (httpClient != null) {
					httpClient.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (httpEntity != null) {
			JSONObject jsonObject = JSON.parseObject(result);
			String errcode = jsonObject.getString("errcode");
			if ("0".equals(errcode)) {
				//获取成功
				userId = jsonObject.getString("userid");
			} else if ("46004".equals(errcode)) {
				// 该用户不存在
				System.out.println("该用户不存在");
			}
			else if ("40014".equals(errcode) || "42001".equals(errcode) || "41001".equals(errcode)) {
				// 重新获取accessToken
				accessToken = this.setAccessToken();
				// 获取accessToken后重新获取userId
				if (accessToken != null) {
					userId = this.tel2userId(userTel);
				}
			} else {
				// 获取失败
				System.out.println("获取失败");
			}
		}
		return userId;

	}

	private String setAccessToken() {
		// 创建客户端
		CloseableHttpClient httpClient = HttpClients.createDefault();
		// 创建一个get请求
		HttpGet httpGet = new HttpGet(("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ww03d30aa489ee2dd8&corpsecret=67qYYez9ivfpRUZk_ihsROeht4z5dnO52QBLM9_BowM"));
		CloseableHttpResponse response = null;
		// 发送请求并获取返回结果
		try {
			response = httpClient.execute(httpGet);
			if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
				//获取返回body
				HttpEntity httpEntity = response.getEntity();
				// 创建输出流
				BufferedWriter bw = new BufferedWriter(new FileWriter("src/main/resources/accesstoken.txt"));
				// 转成String
				String result = EntityUtils.toString(httpEntity,"UTF-8");
				JSONObject jsonObject = JSONObject.parseObject(result);
				accessToken = jsonObject.getString("access_token");
				if (accessToken != null && accessToken.length() > 0) {
					bw.write(accessToken);
				}
				bw.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if (httpClient != null) {
					httpClient.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return accessToken;
	}


	private String getAccessToken() {
		// 读取文件
		FileReader in;
		String accessToken = "";

		try {
			in = new FileReader("src/main/resources/accesstoken.txt");
			BufferedReader br = new BufferedReader(in);
			String str;
			while ((str = br.readLine()) != null) {
				br.close();
				return str;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return accessToken;
	}


	@RequestMapping("dayremove")
	public String dayremove(@RequestParam(value="rcid") Long rcid){
		ScheduleList rc = daydao.findOne(rcid);
		
		daydao.delete(rc);
		
		return "/daymanage";
	}
	
	/**
	 * 一下是日历controller
	 * @return
	 */
	@RequestMapping("daycalendar")
	private String daycalendar() {
		return "daymanage/daycalendar";
	}

//	@RequestMapping("mycalendarload")
//	public void mycalendarload(@SessionAttribute("userId") Long userid,HttpServletResponse response) throws IOException{
//		List<ScheduleList> se = dayser.aboutmeschedule(userid);
//		
//		for (ScheduleList scheduleList : se) {
//			System.out.println(scheduleList);
//		}
//		
//		String json = JSONObject.toJSONString(se);
//		response.setHeader("Cache-Control", "no-cache");
//		response.setContentType("text/json;charset=UTF-8");
//		response.getWriter().write(json);
//		
//	}
	
	@RequestMapping("mycalendarload")
	public @ResponseBody List<ScheduleList> mycalendarload(@SessionAttribute("userId") Long userid,HttpServletResponse response) throws IOException{
		List<ScheduleList> se = dayser.aboutmeschedule(userid);
		
		return se;
	}
}
